package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"order/models"
	"order/util"
	"path/filepath"
	"strconv"
	"strings"
)

type ShopController struct {
	beego.Controller
}
type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	name := c.GetString("name")
	address := c.GetString("address")
	tel := c.GetString("tel")
	cate := c.GetString("cate")
	if !util.IsValidChinese(name) {
		data := JsonRes{
			Code: 500,
			Msg:  "名称必须是中文2-4个汉字",
			Data: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	}
	if !util.IsValidPhone(tel) {
		data := JsonRes{
			Code: 500,
			Msg:  "手机号码格式有误",
			Data: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	}
	shop := models.Shop{
		Name:    name,
		Address: address,
		Tel:     tel,
		Cate:    cate,
	}
	err := models.Add(&shop)
	if err != nil {
		data := JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	} else {
		//fmt.Println("插入的id为",shop.Id)
		key := "shop-" + strconv.Itoa(shop.Id)
		jsonByte, _ := json.Marshal(shop)
		models.Rdb.Set(key, string(jsonByte), 0)
		data := JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	}
}
func (c *ShopController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 3)
	key := "page-" + strconv.Itoa(page) + "-" + strconv.Itoa(pageSize)
	val, err := models.Rdb.Get(key).Result()
	pageData := make(map[string]interface{})
	if err != nil {
		shops, total, err := models.VideoPage(page, pageSize)
		if err != nil {
			data := JsonRes{
				Code: 500,
				Msg:  "查询失败",
				Data: nil,
			}
			c.Data["json"] = data
			c.ServeJSON()
		}

		pageData["shops"] = shops
		pageData["total"] = total
		jsonByte, _ := json.Marshal(pageData)
		models.Rdb.Set(key, string(jsonByte), 0)
		data := JsonRes{
			Code: 200,
			Msg:  "查询成功-数据库",
			Data: pageData,
		}
		c.Data["json"] = data
		c.ServeJSON()
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功-缓存",
			Data: pageData,
		}
		c.ServeJSON()
	}

}
func (c *ShopController) Del() {
	id, _ := c.GetInt("id")
	err := models.Del(id)
	if err != nil {
		data := JsonRes{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	} else {
		data := JsonRes{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	}
}

// 详情
func (c *ShopController) Show() {
	id, _ := c.GetInt("id")
	key := "shop-" + strconv.Itoa(id) //shop-1 shop-2 shop-100
	var shop models.Shop
	val, err := models.Rdb.Get(key).Result()
	if err != nil {
		err = models.DB.Model(&shop).Where("id=?", id).First(&shop).Error
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "展示失效",
				Data: val,
			}
			c.ServeJSON()
		}
		jsonByte, _ := json.Marshal(shop)
		models.Rdb.Set(key, string(jsonByte), 0)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "展示成功-数据库",
			Data: shop,
		}
		c.ServeJSON()
	} else {
		json.Unmarshal([]byte(val), &shop)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "展示成功-缓存",
			Data: shop,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		data := JsonRes{
			Code: 500,
			Msg:  "文件获取失败",
			Data: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	}
	defer file.Close()
	//文件大小
	if header.Size > 2*1024*1024 {
		data := JsonRes{
			Code: 500,
			Msg:  "文件过大，不能超过2M",
			Data: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	}
	//文件类型检查
	allowedExt := map[string]bool{
		".png":  true,
		".jpg":  true,
		".jpeg": true,
	}
	ext := strings.ToLower(filepath.Ext(header.Filename))
	if !allowedExt[ext] {
		data := JsonRes{
			Code: 500,
			Msg:  "文件类型错误,只能是png,jpg,jpeg",
			Data: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		data := JsonRes{
			Code: 500,
			Msg:  "文件上传失败",
			Data: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	} else {
		imgSrc := "http://localhost:8080/" + path
		data := JsonRes{
			Code: 200,
			Msg:  "文件上传成功",
			Data: imgSrc,
		}
		c.Data["json"] = data
		c.ServeJSON()
	}
}
